package com.sky.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.domain.Tag;
import com.sky.mapper.TagMapper;
import com.sky.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * @author 尹稳健~
 * @version 1.0
 */
@Controller
@RequestMapping("/admin")
public class TagController {

    @Autowired
    private TagService tagService;

    // 获取所有的tag标签
    @GetMapping("/tags")
    public String tags(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum,
                       Model model){
        PageHelper.startPage(pageNum,10);
        List<Tag> tagList = tagService.getAllTag();
        PageInfo<Tag> pageInfo = new PageInfo<>(tagList);
        model.addAttribute("pageInfo",pageInfo);
        return "admin/tags";

    }

    // 添加页面
    @GetMapping("/tags/input")
    public String input(Model model){
        Tag tag = new Tag();
        model.addAttribute("tag",tag);
        return "admin/tags_input";
    }

    // 添加数据
    @PostMapping("/tags")
    public String savePost(Tag tag, RedirectAttributes attributes){
        if (tagService.getTagByName(tag.getName()) != null){
            attributes.addFlashAttribute("message","标签名称重复，请换一个！");
            return "redirect:/admin/tags";
        }else {
            tagService.saveTag(tag);
            attributes.addFlashAttribute("message", "添加成功！");
            return "redirect:/admin/tags";
        }
    }

    // 跳转更新页面
    @GetMapping("/tags/{id}/input")
    public String editTag(@PathVariable("id") Long id,Model model){
        model.addAttribute("tag",tagService.getTag(id));
        return "admin/tags_input";
    }

    @PostMapping("/tags/{id}")
    public String editPost(@PathVariable("id") Long id,
                           Tag tag,RedirectAttributes attributes){
        if (tagService.getTagByName(tag.getName())!=null){
            attributes.addFlashAttribute("message","标签名称重复，请换一个！");
        }else{
            tagService.updateTag(tag);
            attributes.addFlashAttribute("message","更新成功！");
        }
        return "redirect:/admin/tags";
    }

    @GetMapping("/tags/{id}/delete")
    public String delete(@PathVariable("id") Long id ,RedirectAttributes attributes){
        tagService.deleteTag(id);
        attributes.addFlashAttribute("message","删除成功！");
        return "redirect:/admin/tags";
    }

}
